package com.yingpai.fitness.dvp_2_0.main.activity.mine.integral;

import android.graphics.Typeface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.widget.NestedScrollView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.yingpai.fitness.R;
import com.yingpai.fitness.dvp_2_0.common.activity.CommonActivity;
import com.yingpai.fitness.dvp_2_0.common.adapter.BaseAdapterHelper;
import com.yingpai.fitness.dvp_2_0.common.adapter.QuickAdapter;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.callback.Callback;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.request.RequestType;
import com.yingpai.fitness.dvp_2_0.common.util.constant.Contacts;
import com.yingpai.fitness.dvp_2_0.common.view.XGridView;
import com.yingpai.fitness.dvp_2_0.main.bean.integral.IntegralDetailDayBean;
import com.yingpai.fitness.dvp_2_0.main.bean.integral.IntegralDetailMonthBean;
import com.yingpai.fitness.dvp_2_0.main.bean.integral.IntegralMallBean;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Constant;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Url;
import com.yingpai.fitness.dvp_2_0.main.widget.NestedExpandaleListView;
import com.yingpai.fitness.dvp_2_0.main.widget.round.RCRelativeLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 积分商城
 * Created by ASUS on 2018/12/17.
 */

public class IntegralMallActivity extends CommonActivity implements OnRefreshLoadMoreListener {

    @BindView(R.id.integral)
    TextView integral;
    @BindView(R.id.integral_mall)
    TextView integralMall;
    @BindView(R.id.integral_detail)
    TextView integralDetail;
    @BindView(R.id.listview)
    NestedExpandaleListView listview;
    @BindView(R.id.gridview)
    XGridView gridview;
    @BindView(R.id.nested_scroll_view)
    NestedScrollView nestedScrollView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private MyExpandableListAdapter detailExpandAdapter;
    List<IntegralDetailMonthBean.DataBean> list = new ArrayList<>();
    private int pageNumber = 1;
    private int pageSize = 10;
    private QuickAdapter<IntegralMallBean.DataBean.RowsBean> mallAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusFlag(Contacts.NORMAL_STATUS);
        setContentView(R.layout.dvp_2_0_activity_integral_mall);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void initView() {
        setTitle("积分商城");
        refreshLayout.setOnRefreshLoadMoreListener(this);
        refreshLayout.setRefreshHeader(new MaterialHeader(context).setColorSchemeResources(R.color.common_color));

        integralMall.setTextColor(getResources().getColor(R.color.common_color));
        integralMall.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
        integralDetail.setTextColor(getResources().getColor(R.color.integral_textColor));
        integralDetail.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
        gridview.setVisibility(View.VISIBLE);
        listview.setVisibility(View.GONE);

        mallAdapter = new QuickAdapter<IntegralMallBean.DataBean.RowsBean>(this, R.layout.item_integral_mall) {
            @Override
            protected void convert(BaseAdapterHelper helper, IntegralMallBean.DataBean.RowsBean item) {
                ImageView photo = helper.getView(R.id.photo);
                Glide.with(context)
                        .load(item.getPhotoUrl().split(",")[0])
                        .error(R.mipmap.default_small_bg)
                        .into(photo);
                RCRelativeLayout rc_layout = helper.getView(R.id.rc_layout);
                rc_layout.setTopLeftRadius(3);
                rc_layout.setTopRightRadius(3);
                rc_layout.setBottomLeftRadius(3);
                rc_layout.setBottomRightRadius(3);
                helper.setText(R.id.title, item.getName());
                helper.setText(R.id.integral, item.getExchange() + "");
            }
        };

        gridview.setAdapter(mallAdapter);
        gridview.setFocusable(false);
        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (mallAdapter.getItem(position).getDictVal() == Constant.NUM_1) {
                    Bundle bundle = new Bundle();
                    bundle.putString("id", mallAdapter.getItem(position).getId());
                    startActivity(IntegralMallVipCardActivity.class, bundle);
                } else if (mallAdapter.getItem(position).getDictVal() == Constant.NUM_2) {
                    Bundle bundle = new Bundle();
                    bundle.putString("id", mallAdapter.getItem(position).getId());
                    startActivity(IntegralMallCouponActivity.class, bundle);
                } else if (mallAdapter.getItem(position).getDictVal() == Constant.NUM_3) {
                    Bundle bundle = new Bundle();
                    bundle.putString("id", mallAdapter.getItem(position).getId());
                    startActivity(IntegralMallShopDetailActivity.class, bundle);
                }
            }
        });


        detailExpandAdapter = new MyExpandableListAdapter(list);
        listview.setGroupIndicator(null);
        listview.setAdapter(detailExpandAdapter);
        listview.setFocusable(false);
        listview.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, final int groupPosition, long id) {
                if (listview.isGroupExpanded(groupPosition)) {
                    listview.collapseGroup(groupPosition);
                } else {
                    if (detailExpandAdapter.getChildrenCount(groupPosition) != 0) {
                        listview.expandGroup(groupPosition, true);
                    } else {
                        showDialog(IntegralMallActivity.this, null);
                        HashMap<String, Object> params = new HashMap();
                        params.put("date", list.get(groupPosition).getOprerateDate());
                        finalOkGo.requestEncrypt(RequestType.POSTENCRYPT, Contacts.HOST_SERVER + Url.GET_INTEGRAL_DETAIL_DAY, params, Url.GET_INTEGRAL_DETAIL_DAY, new Callback<IntegralDetailDayBean>() {
                            @Override
                            public void onSuccess(IntegralDetailDayBean integralDetailDayBean) {
                                if (integralDetailDayBean.getCode().equals(Constant.REQUEST_SUCCESS_0)) {
                                    list.get(groupPosition).getData().clear();
                                    list.get(groupPosition).getData().addAll(integralDetailDayBean.getData());
                                    detailExpandAdapter.notifyDataSetChanged();
                                    listview.expandGroup(groupPosition, true);
                                } else {
                                    showToast(integralDetailDayBean.getMessage() + "");
                                }
                                dismissDialog();
                            }

                            @Override
                            public void onError(Response<String> response) {
                                super.onError(response);
                                dismissDialog();
                            }
                        });
                    }
                }
                return true;
            }
        });
    }

    @Override
    protected void initData() {
        pageNumber = 1;
        requestMallData();
    }

    private void requestMallData() {
        showDialog(this, null);
        HashMap<String, Object> params = new HashMap();
        params.put("pageNumber", pageNumber++);
        params.put("pageSize", pageSize);
        finalOkGo.requestEncrypt(RequestType.POSTENCRYPT, Contacts.HOST_SERVER + Url.GET_INTEGRAL_MALL,
                params, Url.GET_INTEGRAL_MALL, new Callback<IntegralMallBean>() {
            @Override
            public void onSuccess(IntegralMallBean integralMallBean) {
                if (integralMallBean.getCode().equals(Constant.REQUEST_SUCCESS_0)) {
                    integral.setText(integralMallBean.getData().getMyPoint() + "");
                    if (pageNumber - 1 == 1) {
                        mallAdapter.clear();
                        mallAdapter.addAll(integralMallBean.getData().getRows());
                    } else {
                        mallAdapter.addAll(integralMallBean.getData().getRows());
                    }

                    int pagecount;
                    if (integralMallBean.getData().getTotal() % pageSize == 0) {
                        pagecount = integralMallBean.getData().getTotal() / pageSize;
                    } else {
                        pagecount = integralMallBean.getData().getTotal() / pageSize + 1;
                    }
                    if (pageNumber > pagecount) {
                        refreshLayout.setNoMoreData(true);
                        refreshLayout.finishLoadMoreWithNoMoreData();
                    } else {
                        refreshLayout.setNoMoreData(false);
                    }

                    refreshLayout.finishRefresh();
                    refreshLayout.finishLoadMore();
                    mallAdapter.notifyDataSetChanged();
                } else {
                    showToast(integralMallBean.getMessage() + "");
                }
                dismissDialog();
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                dismissDialog();
            }
        });
    }

    class MyExpandableListAdapter extends BaseExpandableListAdapter {

        private List<IntegralDetailMonthBean.DataBean> list;

        public MyExpandableListAdapter(List<IntegralDetailMonthBean.DataBean> list) {
            this.list = list;
        }

        @Override
        public int getGroupCount() {
            return list.size();
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            return list.get(groupPosition).getData().size();
        }

        @Override
        public Object getGroup(int groupPosition) {
            return list.get(groupPosition);
        }

        @Override
        public Object getChild(int groupPosition, int childPosition) {
            return list.get(groupPosition).getData().get(childPosition);
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        @Override
        public boolean hasStableIds() {
            return true;
        }

        @Override
        public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.item_integral_detail, null);
            }
            TextView month = convertView.findViewById(R.id.month);
            TextView get = convertView.findViewById(R.id.get);
            TextView expend = convertView.findViewById(R.id.expend);
            month.setText(list.get(groupPosition).getYueF());
            get.setText("获得：" + list.get(groupPosition).getGetPoint());
            expend.setText("支出：" + list.get(groupPosition).getOutlayPoint());
            ImageView arrow = convertView.findViewById(R.id.arrow);
            if (list.get(groupPosition).isOpen()) {
                arrow.setImageResource(R.mipmap.arrow_top);
            } else {
                arrow.setImageResource(R.mipmap.arrow_bottom);
            }
            LinearLayout item_ll = convertView.findViewById(R.id.item_ll);
            View line = convertView.findViewById(R.id.line);
            if (listview.isGroupExpanded(groupPosition)) {
                line.setVisibility(View.GONE);
                item_ll.setBackgroundResource(R.drawable.integral_detail_top_shape);
            } else {
                line.setVisibility(View.VISIBLE);
                item_ll.setBackgroundResource(R.drawable.shape_shop_cart);
            }
            return convertView;
        }

        @Override
        public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.item_integral_detail_child, null);
            }
            TextView type = convertView.findViewById(R.id.type);
            TextView date = convertView.findViewById(R.id.date);
            TextView integral = convertView.findViewById(R.id.integral);
            type.setText(list.get(groupPosition).getData().get(childPosition).getOperatetypeName());
            date.setText(list.get(groupPosition).getData().get(childPosition).getOperateDate());
            integral.setText(list.get(groupPosition).getData().get(childPosition).getPointStr());
            if (list.get(groupPosition).getData().get(childPosition).getPointStatus().equals("add")) {
                integral.setTextColor(getResources().getColor(R.color.common_color));
            } else if (list.get(groupPosition).getData().get(childPosition).getPointStatus().equals("subtract")) {
                integral.setTextColor(getResources().getColor(R.color.integral_textColor));
            }
            LinearLayout child_item_ll = convertView.findViewById(R.id.child_item_ll);
            View line = convertView.findViewById(R.id.line);
            if (childPosition == list.get(groupPosition).getData().size() - 1) {
                line.setVisibility(View.VISIBLE);
                child_item_ll.setBackgroundResource(R.drawable.integral_detail_bottom_shape);
            } else {
                line.setVisibility(View.GONE);
                child_item_ll.setBackgroundResource(R.drawable.integral_detail_bottom_top_shape);
            }
            return convertView;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return false;
        }
    }


    @Override
    @OnClick({R.id.integral_mall, R.id.integral_detail, R.id.to_top, R.id.integral_order})
    public void onViewClicked(View view) {
        super.onViewClicked(view);
        switch (view.getId()) {
            case R.id.integral_mall:
                refreshLayout.setEnableLoadMore(true);
                refreshLayout.setEnableRefresh(true);
                integralMall.setTextColor(getResources().getColor(R.color.common_color));
                integralMall.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                integralDetail.setTextColor(getResources().getColor(R.color.integral_textColor));
                integralDetail.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
                gridview.setVisibility(View.VISIBLE);
                listview.setVisibility(View.GONE);
                break;
            case R.id.integral_detail:
                refreshLayout.setEnableLoadMore(false);
                refreshLayout.setEnableRefresh(false);
                showDialog(this, null);
                integralDetail.setTextColor(getResources().getColor(R.color.common_color));
                integralDetail.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                integralMall.setTextColor(getResources().getColor(R.color.integral_textColor));
                integralMall.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
                listview.setVisibility(View.VISIBLE);
                gridview.setVisibility(View.GONE);
                requestDetailData();
                break;
            case R.id.to_top:
                nestedScrollView.scrollTo(0, 0);
                break;
            case R.id.integral_order:
                startActivity(IntegralOrderListActivity.class);
                break;
        }
    }

    private void requestDetailData() {
        finalOkGo.requestEncrypt(RequestType.POSTENCRYPT, Contacts.HOST_SERVER + Url.GET_INTEGRAL_DETAIL_MONTH,
                null, Url.GET_INTEGRAL_DETAIL_MONTH, new Callback<IntegralDetailMonthBean>() {
            @Override
            public void onSuccess(IntegralDetailMonthBean integralDetailMonthBean) {
                if (integralDetailMonthBean.getCode().equals(Constant.REQUEST_SUCCESS_0)) {
                    list.clear();
                    list.addAll(integralDetailMonthBean.getData());
                    detailExpandAdapter.notifyDataSetChanged();
                    HashMap<String, Object> params = new HashMap();
                    params.put("date", list.get(0).getOprerateDate());
                    finalOkGo.requestEncrypt(RequestType.POSTENCRYPT, Contacts.HOST_SERVER + Url.GET_INTEGRAL_DETAIL_DAY, params, Url.GET_INTEGRAL_DETAIL_DAY, new Callback<IntegralDetailDayBean>() {
                        @Override
                        public void onSuccess(IntegralDetailDayBean integralDetailDayBean) {
                            if (integralDetailDayBean.getCode().equals(Constant.REQUEST_SUCCESS_0)) {
                                list.get(0).getData().clear();
                                list.get(0).getData().addAll(integralDetailDayBean.getData());
                                detailExpandAdapter.notifyDataSetChanged();
                                listview.expandGroup(0, true);
                            } else {
                                showToast(integralDetailDayBean.getMessage() + "");
                            }
                            dismissDialog();
                        }

                        @Override
                        public void onError(Response<String> response) {
                            super.onError(response);
                            dismissDialog();
                        }
                    });
                } else {
                    dismissDialog();
                    showToast(integralDetailMonthBean.getMessage() + "");
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                dismissDialog();
            }
        });
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        requestMallData();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        pageNumber = 1;
        requestMallData();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReceiveIntegralChange(String event){
        if(event.equals("==exchange==")){
            pageNumber = 1;
            HashMap<String, Object> params = new HashMap();
            params.put("pageNumber", pageNumber++);
            params.put("pageSize", pageSize);
            finalOkGo.requestEncrypt(RequestType.POSTENCRYPT, Contacts.HOST_SERVER + Url.GET_INTEGRAL_MALL,
                    params, Url.GET_INTEGRAL_MALL, new Callback<IntegralMallBean>() {
                        @Override
                        public void onSuccess(IntegralMallBean integralMallBean) {
                            if (integralMallBean.getCode().equals(Constant.REQUEST_SUCCESS_0)) {
                                integral.setText(integralMallBean.getData().getMyPoint() + "");
                            } else {
                                showToast(integralMallBean.getMessage() + "");
                            }
                        }

                        @Override
                        public void onError(Response<String> response) {
                            super.onError(response);
                        }
                    });
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
